<!--  -->
<template>
  <div class="page-container">
    <div class="header-panel">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="测站">
          <StbprpSelect v-model="queryParams.stcd" placeholder="请选择测站"></StbprpSelect>
        </el-form-item>

        <el-form-item label="时间">
          <el-date-picker v-model="queryParams.tm" type="datetimerange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="yyyy-MM-dd HH:mm" value-format="yyyy-MM-dd HH:mm"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
            v-hasPermi="['sjcx:hdsqgcx:add']">新增</el-button>

          <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
            v-hasPermi="['sjcx:hdsqgcx:edit']">修改</el-button>

          <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
            v-hasPermi="['sjcx:hdsqgcx:remove']">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="context-panel">
      <div class="context-left">
        <div class="chart" id="chart"></div>
      </div>
      <div class="context-right">
        <el-table :data="tableData" stripe style="width: 100%" v-el-table-infinite-scroll="loadMore" v-loading="loading"
          @selection-change="handleSelectionChange" height="calc(100% - 38px)">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="stcd" align="center" label="测站编码" />
          <el-table-column prop="tm" align="center" label="时间" />
          <el-table-column prop="z" align="center" label="水位" />
          <el-table-column prop="q" align="center" label="流量" />
        </el-table>
        <!-- 底部加载提示 -->
        <div class="load-more" v-if="tableData.length > 0">
          <span v-if="loading">加载中...</span>
          <span v-else-if="noMore">没有更多数据了</span>
          <span v-else>向下滚动加载更多</span>
        </div>
      </div>
    </div>


    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false" append-to-body
      @close="dialogClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <!-- 第一行第一列：测站编码 -->
          <el-col :span="12">
            <el-form-item label="测站编码" prop="stcd">
              <StbprpSelect v-model="form.stcd" placeholder="请选择测站" :disabled="isEdit" style="width: 100%;">
              </StbprpSelect>
            </el-form-item>
          </el-col>

          <!-- 第一行第二列：时间 -->
          <el-col :span="12">
            <el-form-item label="时间" prop="tm">
              <el-date-picker v-model="form.tm" type="datetime" :disabled="isEdit" style="width: 100%;"
                placeholder="选择时间" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第二行第一列：水位 -->
          <el-col :span="12">
            <el-form-item label="水位" prop="z">
              <el-input v-model="form.z" placeholder="请输入水位（如：12.345）" />
            </el-form-item>
          </el-col>

          <!-- 第二行第二列：流量 -->
          <el-col :span="12">
            <el-form-item label="流量" prop="q">
              <el-input v-model="form.q" placeholder="请输入流量（如：123.456）" />
              <span slot="suffix">m³/s</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第三行第一列：断面过水面积 -->
          <el-col :span="12">
            <el-form-item label="断面过水面积" prop="xsa">
              <el-input v-model="form.xsa" placeholder="请输入断面过水面积（如：123.456）" />
              <span slot="suffix">m²</span>
            </el-form-item>
          </el-col>

          <!-- 第三行第二列：断面平均流速 -->
          <el-col :span="12">
            <el-form-item label="断面平均流速" prop="xsavv">
              <el-input v-model="form.xsavv" placeholder="请输入断面平均流速（如：1.234）" />
              <span slot="suffix">m/s</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第四行第一列：断面最大流速 -->
          <el-col :span="12">
            <el-form-item label="断面最大流速" prop="xsmxv">
              <el-input v-model="form.xsmxv" placeholder="请输入断面最大流速（如：1.234）" />
              <span slot="suffix">m/s</span>
            </el-form-item>
          </el-col>

          <!-- 第四行第二列：河水特征码 -->
          <el-col :span="12">
            <el-form-item label="河水特征码" prop="flwchrcd">
              <el-select v-model="form.flwchrcd" placeholder="请选择" style="width: 100%;" clearable>
                <el-option v-for="item in flwchrcdOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第五行第一列：水势 -->
          <el-col :span="12">
            <el-form-item label="水势" prop="wptn">
              <el-select v-model="form.wptn" placeholder="请选择" style="width: 100%;" clearable>
                <el-option v-for="item in wptnOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 第五行第二列：测流方法 -->
          <el-col :span="12">
            <el-form-item label="测流方法" prop="msqmt">
              <el-select v-model="form.msqmt" placeholder="请选择" style="width: 100%;" clearable>
                <el-option v-for="item in msqmtOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 第六行第一列：测积方法 -->
          <el-col :span="12">
            <el-form-item label="测积方法" prop="msamt">
              <el-select v-model="form.msamt" placeholder="请选择" style="width: 100%;" clearable>
                <el-option v-for="item in msamtOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 第六行第二列：测速方法 -->
          <el-col :span="12">
            <el-form-item label="测速方法" prop="msvmt">
              <el-select v-model="form.msvmt" placeholder="请选择" style="width: 100%;" clearable>
                <el-option v-for="item in msvmtOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import StbprpSelect from '@/components/Select/StbprpSelect'
export default {
  components: { StbprpSelect },
  data() {
    return {
      queryParams: {
        tm: []
      },
      allData: [],
      tableData: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      loading: false,
      page: 0,
      pageSize: 20,
      total: null,
      noMore: false,
      isEdit: false,
      // 表单参数
      form: {

      },
      // 表单校验
      rules: {
        stcd: [
          { required: true, message: '请选择测站编码', trigger: 'blur' },
        ],
        tm: [
          { required: true, message: '请选择时间', trigger: 'blur' },
        ],
      },
      flwchrcdOptions: [
        { label: '干涸', value: '1' },
        { label: '断流', value: '2' },
        { label: '流向不定', value: '3' },
        { label: '逆流', value: '4' },
        { label: '起涨', value: '5' },
        { label: '洪峰', value: '6' },
        { label: '水电厂发电流量', value: 'P' }
      ],
      wptnOptions: [
        { label: '落', value: '4' },
        { label: '涨', value: '5' },
        { label: '平', value: '6' }
      ],
      msqmtOptions: [
        { label: '水位流量关系曲线', value: '1' },
        { label: '浮标及溶液测流法', value: '2' },
        { label: '流速仪及量水建筑物', value: '3' },
        { label: '估算法', value: '4' },
        { label: 'ADCP', value: '5' },
        { label: '电功率反推法', value: '6' },
        { label: '其它方法', value: '9' }
      ],
      msamtOptions: [
        { label: '水位面积关系曲线', value: '1' },
        { label: '测深杆或测深锤、铅鱼', value: '2' },
        { label: '回声测深仪', value: '3' },
        { label: 'ADCP', value: '5' },
        { label: '其它方法', value: '9' }
      ],
      msvmtOptions: [
        { label: '流速仪', value: '1' },
        { label: '浮标法', value: '2' },
        { label: '声学法', value: '3' },
        { label: 'ADCP', value: '5' },
        { label: '其它方法', value: '9' }
      ]

    }
  },
  computed: {},
  created() { },
  mounted() {
    this.getList()
  },
  methods: {

    getList() {
      const tm = this.queryParams.tm
      const btm = tm && (tm.length > 0 ? tm[0] : null)
      const etm = tm && (tm.length > 1 ? tm[1] : null)
      this.$request({
        method: 'get',
        url: 'baseApi/st_river_r/getList',
        params: {
          stcd: this.queryParams.stcd,
          btm: btm,
          etm: etm
          // stcd: '11329410',
          // btm: '2021-01-01 00:00',
          // etm: '2021-02-01 23:59'
        }
      }).then((res) => {
        if (res.code === 200) {
          this.allData = res.data
          this.total = res.data.length
          this.page = 1
          const count = Math.min(this.total, this.pageSize);
          this.tableData = res.data.slice(0, count)
          this.initChart()
        }
      })
    },
    handleQuery() {
      if (this.queryParams.stcd == null) {
        this.$message({
          message: '请选择站点',
          type: 'warning'
        });
        return
      };
      this.tableData = [];
      this.page = 0;
      this.noMore = false;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "添加信息";
      this.open = true
    },
    /** 修改按钮操作 */
    async handleUpdate() {
      this.form = {...this.ids[0]}
      this.isEdit = true;
      this.title = "修改信息";
      this.open = true
    },
    /** 删除按钮操作 */
    handleDelete() {
      const ids = this.ids;
      this.$confirm('是否确认删除该条信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$request({
          url: 'baseApi/st_river_r/delete',
          method: 'post',
          data: ids
        }
        ).then(res => {
          this.handleQuery();
          this.$message({
            message: '操作成功',
            type: 'success'
          });
        })

      }).catch(() => { })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let url = ''
          if (this.isEdit) {
            url = 'baseApi/st_river_r/update'
          } else {
            url = 'baseApi/st_river_r/insert'
          }
          this.$request({
            url: url,
            method: 'get',
            params: this.form
          }).then((res) => {
            if (res.code === 200) {
              this.open = false;
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.handleQuery()
            }
          })
        }
      });
    },
    // 加载更多数据
    async loadMore() {
      if (this.loading || this.noMore || this.page === 0) return;

      this.loading = true;
      try {
        await this.simulateRequest();
        const start = this.tableData.length;
        const remainingCount = this.total - start;
        const count = Math.min(this.pageSize, remainingCount);

        if (count <= 0) {
          this.noMore = true;
          return;
        }
        var newData = this.allData.slice(start, start + count)
        this.tableData = [...this.tableData, ...newData];

        if (this.tableData.length >= this.total) {
          this.noMore = true;
        }
      } catch (error) {
        console.error('加载更多数据失败:', error);
        this.$message.error('加载更多数据失败');
      } finally {
        this.loading = false;
      }
    },
    // 模拟请求延迟
    simulateRequest() {
      return new Promise(resolve => setTimeout(resolve, 800));
    },
    initChart() {
      var chartDom = document.getElementById('chart');
      var myChart = echarts.init(chartDom);
      const data = this.allData
      const z_data = data.map(item => [item.tm, item.z])
      const q_data = data.map(item => [item.tm, item.q])
      const zyMin = Math.floor(Math.min(...data.map(item => item.z)))
      const zyMax = Math.ceil(Math.max(...data.map(item => item.z)))
      const qyMin = Math.floor(Math.min(...data.map(item => item.q)))
      const qyMax = Math.ceil(Math.max(...data.map(item => item.q)))
      var option = {
        title: {
          text: '河道水情过程线',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          }
        },
        legend: {
          // 开启图例
          show: true,
          top: '5%', // 距离顶部10%
        },
        grid: {
          top: '10%',
          left: '5%',
          right: '5%',
          containLabel: true
        },
        toolbox: {
          feature: {
            restore: {},
            saveAsImage: {}
          }
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 100,
            xAxisIndex: [0, 1]
          }
        ],
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            axisLine: { onZero: true },
          }
        ],
        yAxis: [
          {
            name: '水位(m)',
            type: 'value',
            axisLabel: {
              color: '#409EFF'
            },
            axisLine: {
              lineStyle: {
                color: '#409EFF'
              }
            },
            min: zyMin,
            max: zyMax
          },
          {
            name: '流量(m³/s)',
            type: 'value',
            axisLabel: {
              color: '#2be943'
            },
            axisLine: {
              lineStyle: {
                color: '#2be943'
              }
            },
            min: qyMin,
            max: qyMax
          },
        ],
        series: [
          {
            name: '水位',
            type: 'line',
            data: z_data,
            yAxisIndex: 0
          }, {
            name: '流量',
            type: 'line',
            data: q_data,
            yAxisIndex: 1
          }
        ]
      };


      option && myChart.setOption(option);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection;
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    dialogClose() {
      this.isEdit = false;
      this.$data.form = this.$options.data().form
      this.$refs.form && this.$refs.form.resetFields()
    }
  },
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类样式
.context-panel {
  display: flex;
  flex-direction: row;
  height: calc(100% - 50px);
  width: 100%;

  .context-left {
    flex: 5;
    border: 2px dashed #ddd;
  }

  .context-right {
    margin-left: 5px;
    flex: 3;
    overflow: hidden;
  }

  .chart {
    height: 100%;
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
  }
}

.load-more {
  text-align: center;
  padding: 10px;
  color: #1f4fec;
  font-size: 14px;
  background: #f8f9fa;
  border-top: 1px solid #ebeef5;
}
</style>